/*=====================================================
Critical Links
Auto Configuration Server

Authors:
	Rui Eduardo Gouveia Gil - r-gil@critical-links.com

Date: 2011
Version 0.1
=======================================================*/
GroupPanel = function(group,parent) {
	this.group = group;
	this.parent = parent;

	this.deviceList = new Ext.grid.GridPanel({
        region: 'north',
        border: false,
        split: true,
        height: 350,
        minSize: 100,
        maxSize: 600,     
        columns: [{ header: '', width: 30, renderer: this.renderStatus, dataIndex: 'Status', sortable: true, fixed: true},
        		  { header: "Name", dataIndex: 'Name', width: 320, sortable: true},
        		  { header: "Ip", dataIndex: 'Ip', width: 90, sortable: true, fixed: true},
        		  { header: "Release", dataIndex: 'Release', width: 120, sortable: true},
        		  { header: "Configuration", dataIndex: 'Configuration', width: 100, sortable: true},
        		  { header: "Last Contact On", dataIndex: 'LastContactOn', width: 120, sortable: true, fixed: true},
        		  { header: "License", dataIndex: 'License', width: 110, sortable: true, fixed: true},
        		  { header: "Customer", dataIndex: 'Customer', width: 150, sortable: true}],
        store: new Ext.data.ArrayStore({fields: ['Status','Name','Ip','Release','Configuration','LastContactOn','License','Customer','Device']})
    });

    this.deviceList.store.setDefaultSort('LastContactOn', "DESC");

	this.logList = new Ext.grid.GridPanel({
		title: 'Devices contact log',
		region: 'center',
        border: false,
        split: true,
        columns: [{ header: 'Level', width: 60, renderer: this.renderLogLevel, dataIndex: 'Level', sortable: true, fixed: true},
        		  { header: "Time", dataIndex: 'Time', width: 120, sortable: true, fixed: true},
        		  { header: "Ip", dataIndex: 'Ip', width: 100, sortable: true, fixed: true},
        		  { header: "Release", dataIndex: 'Release', width: 120, sortable: true},
//        		  { header: "Command", dataIndex: 'Command', width: 100, sortable: true},
//        		  { header: "Result", dataIndex: 'Result', width: 120, sortable: true},
        		  { header: "Message", dataIndex: 'Message', width: 300, sortable: true}],
        store: new Ext.data.ArrayStore({fields: ['Level','Time','Ip','Release','Command','Result','Message','Log']})
    });

    this.logList.store.setDefaultSort('LastContactOn', "DESC");

    GroupPanel.superclass.constructor.call(this, {
        closable: true,
		layout: 'border',
    	autoDestroy: true,
        id: this.group.tid,
    	iconCls:'group-icon',
        title: this.group.text,
        tabTip: this.group.description,
        items: [this.deviceList,this.logList],
        loadMask: {msg:'Loading Feed...'},
		tbar:[{text:'Edit Group', tooltip: {title:'Edit the group.'}, iconCls: 'edit-group-icon', handler: this.showEditGroup, scope:this },
			  {text:'New Device', tooltip: {title:'Create a new device.'}, iconCls: 'new-device-icon', handler: this.showNewDevice, scope:this },
        	  {id:'openDevice'+this.group.tid, text:'Open Device', tooltip: {title:'Open a device tab.'}, iconCls: 'open-device-icon', handler: this.openDevice, scope:this },
        	  {id:'editDevice'+this.group.tid, text:'Edit Device', tooltip: {title:'Edit a device.'}, iconCls: 'edit-device-icon', handler: this.showEditDevice, scope:this },
        	  {id:'deleteDevice'+this.group.tid, text:'Delete Device', tooltip: {title:'Delete a device.'}, iconCls: 'delete-device-icon', handler: this.deleteDevice, scope:this },
        	  {text:'Refresh', tooltip: {title:'Refresh device list.'}, iconCls: 'refresh-list-icon', handler: this.populateDevices, scope:this }]
    });
    

	this.gsm = this.deviceList.getSelectionModel();
    this.gsm.on('rowselect', this.onRowSelect, this);

    this.deviceList.on('rowdblclick', this.onRowDblClick, this);
	this.deviceList.on('contextmenu', this.onContextMenu, this);
    this.deviceList.on('rowcontextmenu', this.onRowContextMenu, this);

	this.populateDevices();
    this.getTopToolbar().items.get('openDevice'+this.group.tid).setDisabled(true);
    this.getTopToolbar().items.get('editDevice'+this.group.tid).setDisabled(true);
	this.getTopToolbar().items.get('deleteDevice'+this.group.tid).setDisabled(true);
	
    this.addEvents({validgroup: true, createdevice:true, savedevice:true});
    
	this.on('close', this.onClose, this);
	this.task = Ext.TaskMgr.start({run: this.onTimer, interval: 60000, scope: this});
 };

Ext.QuickTips.init();
Ext.extend(GroupPanel, Ext.Panel, {
	onClose : function(device) {
		Ext.TaskMgr.stop(this.task);
	},	

	refresh : function(group) {
		if(group instanceof Group) {
			this.group = group;
			this.setTitle(this.group.text);
			this.onTimer();
		} else {
			this.populateDevices();
		}
	},

	showEditGroup : function(){
        if(!this.winGroup){
            this.winGroup = new GroupWindow();
            this.winGroup.on('validgroup', this.cbShowEditGroup, this);
        }

        this.winGroup.show(this.group);
	},
	
	cbShowEditGroup : function(xml){
		this.group = new Group(xml);
		this.setTitle(this.group.text);
       	this.parent.fireEvent('refreshtree');
	},

	onTimer : function() {
		SGui.getGroupDevices(this.group.id,this.cbRefreshDevices,this);
	},	
	
	cbRefreshDevices : function(obj,result){
		if(result) {	
			if(result instanceof Array) {			
				for(var i=0; i<result.length; i++)
					obj.updateDevice(result[i]);
			} else {
				obj.updateDevice(result);
			}
		}
	},
	
	onContextMenu : function(e) {
        if(!this.menu){ 
            this.menu = new Ext.menu.Menu({
                items: [{
                    id:'cm-new-device'+this.group.id,
                    iconCls:'new-device-icon',
                    text:'New Device',
                    scope: this,
                    handler: this.showNewDevice
                },{
                    id:'open'+this.group.tid,
                    iconCls:'open-device-icon',
                    text:'Open',
                    scope: this,
                    handler: this.contextOpen
                },{
                    id:'edit'+this.group.tid,
                    iconCls:'edit-device-icon',
                    text:'Edit',
                    scope: this,
                    handler: this.contextEdit
                },{
                	id:'remove'+this.group.tid,
                    text:'Remove',
                    iconCls:'delete-device-icon',
                    scope: this,
                    handler: this.contextRemove
                }]
            });
            
            this.menu.on('hide', this.onContextHide, this);
        }

		e.stopEvent();

        this.menu.items.get('open'+this.group.tid).setDisabled(true);
        this.menu.items.get('edit'+this.group.tid).setDisabled(true);
        this.menu.items.get('remove'+this.group.tid).setDisabled(true);

		this.menu.showAt(e.getXY());
	},

	onRowContextMenu : function(grid, index, e){
        if(!this.menu){ 
            this.menu = new Ext.menu.Menu({
                items: [{
                    id:'cm-new-device'+this.group.id,
                    iconCls:'new-device-icon',
                    text:'New Device',
                    scope: this,
                    handler: this.showNewDevice
                },{
                    id:'open'+this.group.tid,
                    iconCls:'open-device-icon',
                    text:'Open',
                    scope: this,
                    handler: this.contextOpen
                },{
                    id:'edit'+this.group.tid,
                    iconCls:'edit-device-icon',
                    text:'Edit',
                    scope: this,
                    handler: this.contextEdit
                },{
                	id:'remove'+this.group.tid,
                    text:'Remove',
                    iconCls:'delete-device-icon',
                    scope: this,
                    handler: this.contextRemove
                }]
            });
            
            this.menu.on('hide', this.onContextHide, this);
        }

        e.stopEvent();
 
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }

        this.ctxRow = this.deviceList.view.getRow(index);
        this.ctxRecord = this.deviceList.store.getAt(index);
        Ext.fly(this.ctxRow).addClass('x-node-ctx');
        
        this.menu.items.get('open'+this.group.tid).setDisabled(false);
        this.menu.items.get('edit'+this.group.tid).setDisabled(false);
        this.menu.items.get('remove'+this.group.tid).setDisabled(false);

        this.menu.showAt(e.getXY());
	},

    onContextHide : function(){
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }
    },
	
	contextOpen : function(){
		this.deviceSelected = this.ctxRecord.get('Device');
		this.openDevice();
	},

	contextEdit : function(){
		this.deviceSelected = this.ctxRecord.get('Device');
		this.showEditDevice();
	},

	contextRemove : function(){
		this.deviceSelected = this.ctxRecord.get('Device');
		this.deleteDevice();
	},

	onRowSelect : function(sm, index, record){
    	this.getTopToolbar().items.get('openDevice'+this.group.tid).setDisabled(false);
	    this.getTopToolbar().items.get('editDevice'+this.group.tid).setDisabled(false);
		this.getTopToolbar().items.get('deleteDevice'+this.group.tid).setDisabled(false);
		
		this.deviceSelected = record.get('Device');
		this.refreshDeviceLog();
	},
	
	onRowDblClick : function(record){
		record = (record && record.data) ? record : this.gsm.getSelected();
		this.deviceSelected = record.get('Device');
		this.openDevice();		
	},

	showNewDevice : function(){
        if(!this.winDevice){
            this.winDevice = new DeviceWindow(this.group);
            this.winDevice.on('createdevice', this.vCreateDevice, this);
            this.winDevice.on('savedevice', this.vUpdateDevice, this);
        }

        this.winDevice.show();
	},
	
	openDevice : function(){
		this.parent.load(this.deviceSelected);
	},

	showEditDevice : function(){
        if(!this.winDevice){
            this.winDevice = new DeviceWindow(this.group,this.deviceSelected);
            this.winDevice.on('createdevice', this.vCreateDevice, this);
            this.winDevice.on('savedevice', this.vUpdateDevice, this);
        }

        this.winDevice.show(this.deviceSelected);
	},
	
	vCreateDevice : function(xml){
		this.updateDevice(xml);
		this.parent.fireEvent('refreshtree');
	},

	vUpdateDevice : function(xml){
		var old = this.deviceSelected;
		this.updateDevice(xml);
		this.parent.fireEvent('refreshtree');
		this.parent.fireEvent('refreshdevice',new Device(xml),old);
	},

	deleteDevice : function(){		
		Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete the device?', function(btn)
		{
			if(btn == 'yes')
			{
				this.deviceList.el.mask('Deleting Device...', 'x-mask-loading');
				SGui.removeDevice(this.deviceSelected.id,this.cbDeleteDevice,this);
			}
		},this);
	},

	cbDeleteDevice : function(obj,result){
		obj.deviceList.el.unmask();
		if(result)
		{
			if(result instanceof Array && result[0] == '-1')
			{
				Ext.MessageBox.show({title: 'Error', msg: result[1], buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
				return;
			}
			else if(result == '-1')
			{
				Ext.MessageBox.show({title: 'Error', msg: 'Protocol Error! Please check the logs for more information.', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
				return;
			}
			
			for(var i=0; i<obj.deviceList.store.getCount(); i++) {
				if(obj.deviceList.store.getAt(i).get('Device').id == obj.deviceSelected.id) {
					obj.deviceList.store.removeAt(i);
					break;
				}
			}
			obj.parent.unload(obj.deviceSelected);
			obj.deviceSelected = 0;
		}
		obj.parent.fireEvent('refreshtree');
	},

	populateDevices : function() {
		SGui.getGroupDevices(this.group.id,this.cbPopulateDevices,this);
		this.getTopToolbar().items.get('openDevice'+this.group.tid).setDisabled(true);
	    this.getTopToolbar().items.get('editDevice'+this.group.tid).setDisabled(true);
		this.getTopToolbar().items.get('deleteDevice'+this.group.tid).setDisabled(true);
		this.deviceSelected = 0;
		if(this.deviceList.el)
			this.deviceList.el.mask('Loading Devices...', 'x-mask-loading');
	},

	cbPopulateDevices : function(obj,result){
		obj.deviceList.store.removeAll();
		obj.logList.store.removeAll();
		obj.deviceSelected = 0;
		if(result) {	
			if(result instanceof Array) {			
				for(var i=0; i<result.length; i++)
					obj.updateDevice(result[i]);
			} else {
				obj.updateDevice(result);
			}
		}
		if(obj.deviceList.el)
			obj.deviceList.el.unmask();
	},
	
	updateDevice : function(xml) {
		var device = new Device(xml);
		
		for(var i=0; i<this.deviceList.store.getCount(); i++) {
			if(this.deviceList.store.getAt(i).get('Device').id == device.id) {
				this.deviceList.store.getAt(i).set('Status',device.status);
				this.deviceList.store.getAt(i).set('Name',device.name);
				this.deviceList.store.getAt(i).set('Ip',device.ip);
				this.deviceList.store.getAt(i).set('Release',device.release);
				this.deviceList.store.getAt(i).set('Configuration',device.configName);
				this.deviceList.store.getAt(i).set('LastContactOn',device.contactedStr);
				this.deviceList.store.getAt(i).set('License',device.licenseID);
				this.deviceList.store.getAt(i).set('Customer',device.customerName);
				this.deviceList.store.getAt(i).set('Device',device);

				if(this.deviceSelected != 0 && this.deviceSelected.id  == device.id)
					this.refreshDeviceLog();
				return;
			}
		}		
		
		this.deviceList.store.loadData([[device.status,device.name,device.ip,device.release,device.configName,device.contactedStr,device.licenseID,device.customerName,device]],true);
	},
	
	updateLog : function(xml) {
		var log = new Log(xml);
		this.logList.store.loadData([[log.levelStr,log.dateStr,log.ip,log.release,log.command,log.result,log.message,log]],true);
	},

	refreshDeviceLog : function() {
		SGui.getDeviceLogs(this.deviceSelected.id,1,0,20,this.cbRefreshLogs,this);
	},

	cbRefreshLogs : function(obj,result){
		obj.logList.store.removeAll();
		if(result) {	
			if(result instanceof Array) {			
				for(var i=0; i<result.length; i++) {
					var log = new Log(result[i]);
					obj.logList.store.loadData([[log.level,log.dateStr,log.ip,log.release,log.command,log.result,log.message,log]],true);
				}
			} else {
				var log = new Log(result);
				obj.logList.store.loadData([[log.level,log.dateStr,log.ip,log.release,log.command,log.result,log.message,log]],true);
			}
		}
		if(obj.logList.el)
			obj.logList.el.unmask();
	},	

	renderStatus : function(status, metadata){
		if(status == 0) { //DS_PENDING_VALIDATION
			metadata.attr = 'ext:qtip="pending validation"';
			return '<img src=icons/ledyellow.png>';
		} else if(status == 1) { //DS_PENDING_CONFIRMATION
			metadata.attr = 'ext:qtip="pending confirmation"';
			return '<img src=icons/ledyellow.png>';
		} else if(status == 2) { //DS_PENDING_BACKUP_WITH_SOUNDS
			metadata.attr = 'ext:qtip="pending backup with voip sounds"';
			return '<img src=icons/ledorange.png>';
		} else if(status == 3) { //DS_PENDING_BACKUP
			metadata.attr = 'ext:qtip="pending backup"';
			return '<img src=icons/ledorange.png>';
		} else if(status == 4) { //DS_PENDING_TASKS
			metadata.attr = 'ext:qtip="pending tasks"';
			return '<img src=icons/ledorange.png>';
		} else if(status == 5) { //DS_EXECUTING_BACKUP
			metadata.attr = 'ext:qtip="executing backup"';
			return '<img src=icons/ledblue.png>';
		} else if(status == 6) { //DS_EXECUTING_TASKS
			metadata.attr = 'ext:qtip="executing tasks"';
			return '<img src=icons/ledblue.png>';
		} else if(status == 7) { //DS_SYNCHRONIZED
			metadata.attr = 'ext:qtip="online"';
			return '<img src=icons/ledgreen.png>';
		} else {
			metadata.attr = 'ext:qtip="offline"';
			return '<img src=icons/ledgrey.png>';
		}
	},

	renderLogLevel : function(status){
		if(status == 0) { //ACS_LL_DEBUG
			return '<img src=icons/log-trace.png>';
		} else if(status == 1) { //ACS_LL_NOTICE
			return '<img src=icons/log-info.png>';
		} else if(status == 2) { //ACS_LL_WARNING
			return '<img src=icons/log-warning.png>';
		} else if(status == 3) { //ACS_LL_ERROR
			return '<img src=icons/log-error.png>';
		} else {
			return 'none';
		}
	}	
});

Ext.reg('appgrouppanel', GroupPanel);